package com.threeti.mecool.common.resource.filter;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;

import com.threeti.jiayusms.framework.util.Lists;
import com.threeti.mecool.common.resource.Content;
import com.threeti.mecool.common.resource.core.ContentFactory;

public class ContentFilterTwoStepFastMatchStrategy implements ContentFilterStrategy {
	
	private static Logger logger = LoggerFactory.getLogger(ContentFilterTwoStepFastMatchStrategy.class);
	private static ContentFilterTwoStepFastMatchStrategy instance;
	
	public synchronized static ContentFilterStrategy getInstance() {
		if (instance == null) {
			instance = new ContentFilterTwoStepFastMatchStrategy();
		}
		return instance;
	}
	
	private ContentFilterTwoStepFastMatchStrategy() {
	}

	public List<Content> queryForContents(final Content content, ContentFilter filter) throws IOException {
		Validate.notNull(content, "被筛选的目标内容资源不能为空");
		Validate.notNull(filter, "内容资源筛选过滤器不能为空");
		
		final List<Content> result = Lists.newArrayList();
		final ContentTwoStepFastMatchFilter quickMatchKey = (ContentTwoStepFastMatchFilter)filter;
		if (content.getFile().getPath().indexOf(quickMatchKey.getFirstStepMatchKey()) != -1) {
				content.getFile().listFiles(new FileFilter() {
				public boolean accept(File pathname) {
					boolean isMatched = false;
					if (isMatched = pathname.getPath().indexOf(quickMatchKey.getSecondStepMatchKey()) != -1) {
						try {
							result.add(ContentFactory.makeContent(new UrlResource(content.getURL().getProtocol() + ":" + pathname.getAbsolutePath())));
						} catch (Exception e) {
							logger.error("解析内容时产生不可预期的错误，该错误导致内容筛选结果出错", e);
						}
					}
					return isMatched;
				}
			});
		}
		return result;
	}
}
